import React from 'react'
import './comment2.css'
class CommentInput extends React.Component {
  state = {
    list: [
          {
          id: 1,
          userName: '小白',
          commentxt: '躺楼~',
          count: 0
      },
      {
          id: 2,
          userName: '小黑',
          commentxt: '躺楼~',
          count: 0
      }
    ],
    userName: '',
    commentxt: '',
  }
  show = () => {
    const { list } = this.state
    if (list.length >= 1) {
      return (
        <ul>
          {list.map((item,index) => (
            <li key={item.id}>
              <div style={{ fontSize: '20px' }}>评论人：{item.userName}</div>
              <div style={{ fontSize: '14px', marginButton: '10px' }}>
                评论内容：{item.commentxt}
              </div>
              <div style={{fontSize: '10px',float:'right'}}><span style={{marginRight:'10px',color: item.count === 0 ? 'black':'red'}} onClick={()=>this.handleZan(index)}>点赞 {item.count}</span><span onClick={()=>this.handledel(index)}>删除</span></div>
            </li>
          ))}
        </ul>
      )
    } else {
      return <div className='d14'>暂无评论哦~</div>
    }
  }
//   双向绑定
  handleChange = e => {
    // 那value的值赋值给name,name 在一开始布局已经给到e.target
    const { name, value } = e.target
    this.setState({
      [name]: value
    })
  }
//   发表评论
  handleClick = () => {
    const { list, userName, commentxt } = this.state
    console.log(list, userName, commentxt)
    if (userName.trim() === '' || commentxt.trim() === '') {
      alert('评论内容和评论人不得为空')
      return
    }
    let newList = [
      {
        id: Math.random(),
        userName: userName,
        commentxt: commentxt,
        count: 0
      },
      ...list
    ]
    // 刷新
    this.setState({
      list: newList,
      userName: '',
      commentxt: ''
    })
  }
//   删除评论
  handledel(i) {
    //   返回值是被删掉的
      this.state.list.splice(i,1)
      this.setState({
          list: this.state.list
      })

  }
//   点赞
handleZan(i){
    const {list} = this.state
    if(list[i].count === 0) {
        list[i].count = 1
    } else {
        list[i].count = 0
    }
    
    this.setState({
        list:list
    })
}
  render () {
    const { userName, commentxt } = this.state
    return (
      <div className='d1'>
        <input
          type='text'
          value={userName}
          className='d11'
          placeholder='请输入评论人'
          onChange={this.handleChange}
          name='userName'
        ></input>
        <textarea
          rows='7'
          value={commentxt}
          cols='51'
          className='d12'
          placeholder='请输入评论内容'
          onChange={this.handleChange}
          name='commentxt'
        ></textarea>
        <button className='d13' onClick={this.handleClick}>
          发出评论
        </button>
        <div>{this.show()}</div>
      </div>
    )
  }
}

export default CommentInput
